package com.atguigu.yygh.cmn.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import com.atguigu.yygh.cmn.mapper.DictMapper;
import com.atguigu.yygh.model.cmn.Dict;
import com.atguigu.yygh.vo.cmn.DictEeVo;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA
 *
 * @Date: 2022/12/16 - 09:09
 * @Author: Hyoung
 * @Description:
 */
@AllArgsConstructor
@NoArgsConstructor
@Slf4j
// 不要放到容器中，不然会资源占用过多，只用一次
public class DictListener extends AnalysisEventListener<DictEeVo> {

    private DictMapper dictMapper;

    private static final int BATCH_COUNT = 3000;
    List<Dict> list = new ArrayList<Dict>();

    public DictListener(DictMapper baseMapper) {
        this.dictMapper = baseMapper;
    }

    //一行一行读取
    @Override
    public void invoke(DictEeVo dictEeVo, AnalysisContext analysisContext) {
        log.info("解析到一条数据:{}", JSON.toJSONString(dictEeVo));
        //调用方法添加数据库
        Dict dict = new Dict();
        BeanUtils.copyProperties(dictEeVo, dict);
        list.add(dict);
        if (list.size() >= BATCH_COUNT) {
            saveData();
            list.clear();
        }
//        log.info("开始存储数据库！");
//        dictMapper.insert(dict);
//        log.info("存储数据库成功！");
    }

    private void saveData() {
        log.info("{}条数据，开始存储数据库", list.size());
        dictMapper.saveBatch(list);
        log.info("存储数据库成功");
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
        log.info("所有数据解析完成！");
    }
}